package com.newtouch.cq.lang.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.newtouch.cq.lang.em.BaseExceptionEnum;
import com.newtouch.cq.lang.exception.MccBizException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;

/**
 * Servlet工具类
 *
 * @author Alex
 * @date 2020/11/10
 */
public class ServletUtils {

    private static Log log = LogFactory.get(ServletUtils.class);

    /**
     * 获取ServletRequestAttributes
     *
     * @return
     */
    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取HttpSession
     *
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取HttpServletResponse
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }


    /**
     * 输出文件到客户端
     * @param in
     */
    public static void writeToWeb(InputStream in,String fileName) {
        HttpServletResponse response = getResponse();
        try (OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
            response.reset();
            // 设置response的Header

            String userAgent = ServletUtils.getRequest().getHeader("User-Agent");//获取浏览器名（IE/Chome/firefox）
            if ((userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
                fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);// IE浏览器
            } else {
                fileName = new String(fileName.getBytes(CharsetUtil.CHARSET_UTF_8), CharsetUtil.CHARSET_ISO_8859_1);// 谷歌
            }
//        response.addHeader("Content-Length", "" + file.length());
            if(StrUtil.equals(FileUtils.getSuffix(new String(fileName.getBytes(CharsetUtil.CHARSET_UTF_8))),"pdf")) {
                response.addHeader("Content-Disposition", "inline;filename=" + fileName);
                response.setContentType("application/pdf");
            } else {
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setContentType("application/octet-stream");
            }
//            String contentType = ContentTypeEnum.contentType(FileUtils.getSuffix(fileName));
//            if (StrUtil.isNotEmpty(contentType)) {
//                response.setContentType(contentType);
//            }
            byte[] buffer = new byte[1204];
            int byteread;
            while ((byteread = in.read(buffer)) != -1) {
                toClient.write(buffer, 0, byteread);
            }
            toClient.flush();
        } catch (IOException e) {
            LogUtil.error(log, BaseExceptionEnum.FAIL, ExceptionUtil.stacktraceToString(e));
            throw (new MccBizException(BaseExceptionEnum.FAIL)).setMessage(ExceptionUtil.getMessage(e));
        } finally {
            if(ObjectUtil.isNotNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    LogUtil.error(log, BaseExceptionEnum.FAIL, ExceptionUtil.stacktraceToString(e));
                    throw (new MccBizException(BaseExceptionEnum.FAIL)).setMessage(ExceptionUtil.getMessage(e));
                }
            }
        }
    }
}